package com.rw.admin.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.rw.admin.cache.RedisCache;
import com.rw.common.mapper.ConfigInfoMapper;
import com.rw.common.pojo.CarInfo;
import com.rw.common.pojo.ConfigInfo;
import com.rw.admin.service.ConfigInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
* @author rabit
* @description 针对表【config_info】的数据库操作Service实现
* @createDate 2021-12-06 15:10:31
*/
@Service
public class ConfigInfoServiceImpl implements ConfigInfoService {
    @Autowired
    private ConfigInfoMapper configInfoMapper;

    @Autowired
    private RedisCache redisCache;

    @Override
    public List<ConfigInfo> getAll() {
        return configInfoMapper.findAll();
    }

    @Override
    public String getValueByKey(String key) {
        String res  = null;
        //1.先从缓存中去配置文件
        Object o = redisCache.get(key);
        //如果缓存中中没有配置文件情况下：从数据库中取
        if (o == null){
            ConfigInfo param = new ConfigInfo();
            param.setConfigKey(key);
            ConfigInfo config =  configInfoMapper.getValueByKey(param);
            redisCache.set(config.getConfigKey(),config.getConfigValue());
            res = config.getConfigValue();
        }else {
            res = o.toString();
        }

        return res;
    }

    @Override
    public PageInfo getDataByPage(Integer pageNum, Integer limit,ConfigInfo configInfo) {
        PageHelper.startPage(pageNum,limit);
        List<CarInfo> list = configInfoMapper.selectAll(configInfo);
        PageInfo page = new PageInfo(list);
        return page;
    }

    @Override
    public boolean save(ConfigInfo configInfo) {
       int i = configInfoMapper.insertSelective(configInfo);
        return i>0;
    }

    @Override
    public boolean update(ConfigInfo configInfo) {
        if (configInfo.getId()!=null){
            int i =  configInfoMapper.updateByPrimaryKeySelective(configInfo);
            if (i>0){
                redisCache.set(configInfo.getConfigKey(),configInfo.getConfigValue());
            }
            return i>0;
        }
        return false;
    }
}
